﻿/***********************/
/* (c) Alexandru Lungu */
/*  Challenge is Life! */
/* www.challenge-me.ws */
/***********************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Security.Principal;
using Coowork.WcfCommon;
using System.Security.Authentication;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.ServiceModel.Channels;

namespace Coowork.WcfServer
{
    //[3]
    public class ChallengeAuthenticationManager : ServiceAuthenticationManager
    {
        public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
        {
            Credentials credentials = Credentials.FromMessageHeader(message);
            
            CheckCredentials(credentials);

            ChallengeIdentity identity = new ChallengeIdentity(credentials.UserName);
            IPrincipal user = new ChallengePrincipal(identity);
            message.Properties["Principal"] = user;

            return authPolicy;
        }

        public void CheckCredentials(Credentials credentials)
        {
            if (credentials.Expires < DateTime.Now)
                throw new AuthenticationException("Credentials expired!");

      //      if (credentials.UserName != "Alle")
        //        throw new AuthenticationException("Incorrect credentials!");

            // check the user and password against a database; 
            // if not match 
            // throw new AuthenticationException("Incorrect credentials!");
        }
    }

}
